package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class RegularlyClearOrdersTask {
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 处理超时未支付订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void clearPENDINGPAYMENT(){
        log.info("处理超时未支付订单");
        //获取未支付且超时订单
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> orders = ordersMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        if(!orders.isEmpty()){
            orders.forEach(order -> {
                order.setCancelReason("超时取消订单");
                order.setCancelTime(LocalDateTime.now());
                order.setStatus(Orders.CANCELLED);
                ordersMapper.update(order);
            });
        }
    }

    /**
     * 处理派送中订单
     */
    //@Scheduled(cron = "0 4 11 * * ?") //测试使用
    @Scheduled(cron = "0 0 1 * * ?")
    public void clearDELIVERYINPROGRESS(){
        log.info("处理派送中订单");
        //获取未支付且超时订单
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> orders = ordersMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);
        if(!orders.isEmpty()){
            orders.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(time);
                ordersMapper.update(order);
            });
        }
    }
}
